package 别人的教程

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"sync"
)

// 异步下载mp4视频列表

func main() {
	fmt.Println("开始")
	videoURLs := []string{
		"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4",
		"http://vjs.zencdn.net/v/oceans.mp4",
		"https://media.w3.org/2010/05/sintel/trailer.mp4",
	}

	var wg sync.WaitGroup
	for _, url := range videoURLs {
		wg.Add(1)
		go func(url string) {
			defer wg.Done()
			err := downloadVideo(url)
			if err != nil {
				fmt.Printf("Error downloading video from %s: %v\n", url, err)
			} else {
				fmt.Printf("Successfully downloaded video from %s\n", url)
			}
		}(url)
	}
	wg.Wait()
	fmt.Println("结束")
}

func downloadVideo(url string) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	filename := getFilenameFromURL(url)
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.Copy(file, resp.Body)
	return err
}

func getFilenameFromURL(url string) string {
	return url[strings.LastIndex(url, "/")+1:]
}
